package ar.com.ctrln.view.dashboard.calendar;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.EventQueue;
import org.zkoss.zk.ui.event.EventQueues;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.VariableResolver;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.Button;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Constraint;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Row;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Timebox;
import org.zkoss.zul.Window;

import ar.com.ctrln.control.calendar.RegistrarEvento;
import ar.com.ctrln.persistence.model.evento.EventoCalendario;
import ar.com.ctrln.persistence.model.evento.EventoCurso;
import ar.com.ctrln.persistence.model.evento.EventoPersonal;
import ar.com.ctrln.persistence.model.evento.EventoReunion;
import ar.com.ctrln.persistence.model.evento.EventoTicket;
import ar.com.ctrln.persistence.model.evento.TemaEvento;
import ar.com.ctrln.persistence.model.evento.TipoEvento;
import ar.com.ctrln.persistence.model.sistema.cuentas.Autorizacion;
import ar.com.ctrln.view.ui.comportamientoVentana.AbstractMinimizarVentana;

@VariableResolver(org.zkoss.zkplus.spring.DelegatingVariableResolver.class)
public class GenerarEventoController extends AbstractMinimizarVentana {

	private static final long serialVersionUID = -8319277137888452909L;

	@WireVariable
	private RegistrarEvento registrarEvento;

	@Wire
	private Window wGenerarEvento;

	@Wire
	private Combobox cboTipoEvento;

	@Wire
	private Datebox fechaInicio;

	@Wire
	private Datebox fechaFin;

	@Wire
	private Timebox horaInicio;

	@Wire
	private Textbox tbDescripcion;

	@Wire
	private Timebox horaFin;

	@Wire
	private Button bCancelarEvento;

	@Wire
	private Button bGenerarEvento;

	@Wire
	private Button btnAgregarParticipantes;

	@Wire
	private Button btnTemaEvento;

	@Wire
	private Row participantesRow;

	@Wire
	private Row temasEventoRow;

	@Wire
	private Checkbox cboxtodoElDia;

	@SuppressWarnings("rawtypes")
	private EventQueue eventoParticipantes;

	@SuppressWarnings("rawtypes")
	private EventQueue eventoTemas;

	private EventoCalendario evento;

	private TipoEvento tipo;

	private Set<TemaEvento> temas = new HashSet<TemaEvento>();

	@SuppressWarnings("unchecked")
	@Override
	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);

		eventoParticipantes = EventQueues.lookup("seleccionar_participantes",
				EventQueues.DESKTOP, true);
		eventoParticipantes.subscribe(new EventListener<Event>() {
			@Override
			public void onEvent(Event event) throws Exception {

			}
		});

		eventoTemas = EventQueues.lookup("seleccionarTemasEventos",
				EventQueues.DESKTOP, true);
		eventoTemas.subscribe(new EventListener<Event>() {
			@Override
			public void onEvent(Event event) throws Exception {
				temas = (Set<TemaEvento>) event.getData();
				tbDescripcion.setText("");
				for (TemaEvento temaEvento : temas) {
					tbDescripcion.setText(temaEvento.getNombre() + "\n");

				}
			}
		});
		cboTipoEvento.setModel(new ListModelList<TipoEvento>(registrarEvento
				.listarTiposEventos()));

		Calendar calendar = Calendar.getInstance(Locale.getDefault());
		calendar.setTime(new Date());
		calendar.set(Calendar.HOUR, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.MILLISECOND, 0);

		fechaInicio.setValue(calendar.getTime());
		fechaFin.setValue(calendar.getTime());

		fechaFin.setConstraint(new Constraint() {

			@Override
			public void validate(Component arg0, Object arg1)
					throws WrongValueException {
				Date date = (Date) arg1;
				if (arg1 != null && date.before(fechaInicio.getValue())) {
					if (null != horaFin.getValue()
							&& null != horaInicio.getValue()
							&& (horaFin.getValue().before(horaInicio.getValue()))) {
						Clients.showNotification(
								"Modifique la Fecha de Inicio", fechaInicio);
						throw new WrongValueException(arg0,
								"La Fecha de finalizacion debe ser mayor a la Fecha de iniciación");
					}

				}
			}
		});

		horaFin.setConstraint(new Constraint() {

			@Override
			public void validate(Component arg0, Object arg1)
					throws WrongValueException {
				if (fechaInicio.getValue().equals(fechaFin))
					if (arg1 != null
							&& ((Date) arg1).before(horaInicio.getValue())
							&& !cboxtodoElDia.isChecked()) {

						Clients.showNotification(
								"Seleccione Evento de día completo",
								cboxtodoElDia);
						throw new WrongValueException(arg0,
								"La Hora de finalizacion debe ser mayor a la Hora de Inicio");

					}
			}
		});
	}

	@Listen("onClick = #bGenerarEvento")
	public void guardarEvento() {

		Date beginDay = fechaInicio.getValue();
		Date endDay = fechaFin.getValue();
		Calendar calendarDay = Calendar.getInstance(Locale.getDefault());
		if (!cboxtodoElDia.isChecked()) {

			Date horaInicio = this.horaInicio.getValue();
			Date horaFin = this.horaFin.getValue();

			Calendar calendarTime = Calendar.getInstance(Locale.getDefault());
			calendarTime.setTime(horaInicio);

			calendarDay.setTime(beginDay);
			calendarDay.set(Calendar.HOUR_OF_DAY,
					calendarTime.get(Calendar.HOUR_OF_DAY));
			calendarDay.set(Calendar.MINUTE, calendarTime.get(Calendar.MINUTE));

			beginDay = calendarDay.getTime();

			calendarTime.setTime(horaFin);

			calendarDay.setTime(endDay);
			calendarDay.set(Calendar.HOUR_OF_DAY,
					calendarTime.get(Calendar.HOUR_OF_DAY));
			calendarDay.set(Calendar.MINUTE, calendarTime.get(Calendar.MINUTE));
			endDay = calendarDay.getTime();

		} else {
			evento.setBeginDate(beginDay);
			evento.setEndDate(endDay);
			Calendar calendar = Calendar.getInstance(Locale.getDefault());
			calendar.setTime(endDay);
			calendar.set(Calendar.HOUR, 23);
			calendar.set(Calendar.MINUTE, 59);
			calendar.set(Calendar.MILLISECOND, 0);
			evento.setEndDate(calendar.getTime());
		}

		evento.setContentColor(tipo.getColorRelleno());
		evento.setHeaderColor(tipo.getColorTitulo());
		evento.setTipoEvento(tipo);
		evento.setBeginDate(beginDay);
		evento.setEndDate(endDay);
		evento.setLoked(true);
		evento.setTitle(cboTipoEvento.getSelectedItem().getLabel());

		evento.setContent(cboTipoEvento.getSelectedItem().getLabel());
		
		evento.setObservacion(tbDescripcion.getText());

		Autorizacion autorizacion = registrarEvento
				.buscarAutorizacion("ROLE_ADMIN");

		Collection<Autorizacion> autorizaciones = new ArrayList<Autorizacion>();
		autorizaciones.add(autorizacion);

		evento.setAutorizaciones(autorizaciones);

		registrarEvento.nuevoEvento(evento);

		if (evento.getParticipantes() != null
				&& evento.getParticipantes().size() > 0) {
			registrarEvento.nuevoParticipante(evento.getParticipantes());
		}

		wGenerarEvento.onClose();
	}

	@Listen("onClick = #btnAgregarParticipantes")
	public void agregarParticipantes() {
		Executions.createComponents("/zul/calendar/agregarParticipante.zul",
				wGenerarEvento, null);
	}

	@Listen("onSelect = #cboTipoEvento")
	public void seleccionTipoEvento() {
		tipo = cboTipoEvento.getSelectedItem().getValue();
		switch (tipo.getPeso()) {
		case 1:
			evento = null;
			temasEventoRow.setVisible(true);
			participantesRow.setVisible(true);
			evento = (EventoReunion) registrarEvento
					.getEvento(RegistrarEvento.EVENTO_REUNION);
			break;
		case 2:
			evento = null;
			temasEventoRow.setVisible(false);
			participantesRow.setVisible(true);
			evento = (EventoCurso) registrarEvento
					.getEvento(RegistrarEvento.EVENTO_CURSO);
			break;
		case 3:
			evento = null;
			temasEventoRow.setVisible(false);
			participantesRow.setVisible(false);
			evento = (EventoPersonal) registrarEvento
					.getEvento(RegistrarEvento.EVENTO_PERSONAL);
			break;

		default:
			evento = null;
			evento = (EventoTicket) registrarEvento
					.getEvento(RegistrarEvento.EVENTO_PERSONAL);
			temasEventoRow.setVisible(false);
			participantesRow.setVisible(false);
			break;
		}

	}

	@Listen("onClick = #btnTemaEvento")
	public void agregarTemaEvento() {
		wGenerarEvento.setAttribute("temas", temas);
		Executions.createComponents("/zul/calendar/agregarTemaEvento.zul",
				wGenerarEvento, null);
	}
}
